import os
import hashlib

def calculate_file_hash(file_path):
    """计算文件的MD5哈希值"""
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def find_duplicate_files(root_dir):
    """查找指定文件夹及其子文件夹中内容相同的文件"""
    file_hashes = {}
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            file_path = os.path.join(dirpath, filename)
            file_hash = calculate_file_hash(file_path)
            if file_hash in file_hashes:
                file_hashes[file_hash].append(file_path)
            else:
                file_hashes[file_hash] = [file_path]

    # 过滤出内容相同的文件
    duplicate_files = {k: v for k, v in file_hashes.items() if len(v) > 1}
    return duplicate_files

# 指定要搜索的根目录
root_directory = r'D:\fanxinlong\fan_2401\test'

# 查找并打印内容相同的文件
duplicate_files = find_duplicate_files(root_directory)
for file_hash, files in duplicate_files.items():
    print(f"内容相同的文件（哈希值: {file_hash}):")
    for file in files:
        print(f"  {file}")